﻿using System;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using iTunesLib;

namespace Twittscrobbler
{
    class iTunes_scrobble
    {
        private Object formObject_ = null;
        private iTunesApp itunes;

        public iTunes_scrobble(Object formObject)
        {
            formObject_ = formObject;
            //iTunes起動、監視
            itunes = new iTunesApp();
            itunes.OnAboutToPromptUserToQuitEvent +=
              new _IiTunesEvents_OnAboutToPromptUserToQuitEventEventHandler(itunes_OnAboutToPromptUserToQuitEvent);
            itunes.OnPlayerPlayEvent +=
              new _IiTunesEvents_OnPlayerPlayEventEventHandler(itunes_OnPlayerPlayEvent);
        }

        //曲のプレイイベント、Invokeを用いてラベル操作
        public void itunes_OnPlayerPlayEvent(object iTrack)
        {
            IITTrack track = itunes.CurrentTrack;
            if (track != null)
            {
                ((Form1)formObject_).Invoke((System.Windows.Forms.MethodInvoker)delegate()
                {
                    ((Form1)formObject_).name_Change(((Form1)formObject_).name_ + "♬" + track.Name + "/" + track.Artist);

                });

                Marshal.FinalReleaseComObject(track);
            }
        }

        public void itunes_OnAboutToPromptUserToQuitEvent()
        {
            unhock();
            ((Form1)formObject_).Invoke((System.Windows.Forms.MethodInvoker)delegate()
            {
                ((Form1)formObject_).Close();
            });
        }

        //プレイヤー開放
        public void unhock()
        {
            itunes.OnPlayerPlayEvent -=
              new _IiTunesEvents_OnPlayerPlayEventEventHandler(itunes_OnPlayerPlayEvent);
            itunes.OnAboutToPromptUserToQuitEvent -=
              new _IiTunesEvents_OnAboutToPromptUserToQuitEventEventHandler(itunes_OnAboutToPromptUserToQuitEvent);

            Marshal.FinalReleaseComObject(itunes);
        }
    }
}
